<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>async与await封装Ajax请求</title>
</head>

<body>
  <script>
    // 发送ajax请求, 返回结果是Promise对象
    function sendAjax(url) {
      return new Promise((resolve, reject) => {
        // setTimeout(() => {
        //   console.log("响应成功");
        //   resolve("成功");
        // }, 1000);
        // 1.创建对象
        const http = new XMLHttpRequest();
        // 2.初始化
        http.open("GET", url);
        // 3.发送请求
        http.send();
        // 4.响应事件监听
        http.onreadystatechange = function () {
          if (http.readyState === 4) {
            if (http.status >= 200 && http.status < 300) resolve(http.response);
            else reject(http.status);
          }
        }
      })
    }

    async function main() {
      const result1 = await sendAjax("https://api.apiopen.top/getJoke");
      console.log(result1);
      // const result2 = await sendAjax("https://api.apiopen.top/getJoke");
      // console.log(result2);
    }

    main();
  </script>
</body>

</html>